package com.probox.common.security.service;

import com.probox.common.core.constant.CacheConstants;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.domain.R;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.PreAuthorizeException;
import com.probox.common.core.utils.IdUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.ServletUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.ip.IpUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.systemApi.RemoteCustomerService;
import com.probox.systemApi.RemoteUserService;
import com.probox.systemApi.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * token验证处理
 *
 * @author usoft
 */
@Component
public class TokenService {
    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private RemoteUserService remoteUserService;

    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    protected static final long MILLIS_SECOND = 1000;

    /**
     * 创建客户令牌
     */
    public Map<String, Object> createCustoemrToken(LoginUser loginUser) {
        // 生成token
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserid(loginUser.getCustomerInfoAccount().getCustomerUid());
        loginUser.setAccountUid(loginUser.getCustomerInfoAccount().getCustomerAccountUid());
        loginUser.setUsername(loginUser.getCustomerInfoAccount().getAccountName());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        //保存信息到客户token表
        Boolean flag = remoteCustomerService.addCustomerToken(loginUser);
        if (!flag) {
            throw new PreAuthorizeException("保存token失败");
        }
        refreshToken(loginUser);
        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }


    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        Long userId = loginUser.getSysUser().getUserId();
        // 生成token
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(loginUser.getSysUser().getUserName());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        refreshToken(loginUser);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            LoginUser user = redisService.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisService.deleteObject(userKey);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 重新刷新token
     *
     * @param loginUser
     */
    public void reUid(LoginUser loginUser) {
        R<LoginUser> userInfo = remoteUserService.getUserInfo(loginUser.getUsername());
        if (userInfo.getCode() == R.FAIL) throw new BaseException("刷新失败！请联系管理员");
        LoginUser data = userInfo.getData();
        data.setToken(loginUser.getToken());
        data.setUserid(loginUser.getSysUser().getUserId());
        data.setUsername(loginUser.getSysUser().getUserName());
        data.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        //data.setOrgUid(loginUser.getSysUser().getOrganId());
        //data.setDoctorId(loginUser.getSysUser().getDoctorUid());
        refreshToken(data);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", data.getToken());
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + data.getToken(), data, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    public void reUser(LoginUser data) {
        refreshToken(data);
        data.setUsername(data.getSysUser().getUserName());
        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", data.getToken());
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + data.getToken(), data, EXPIRE_TIME, TimeUnit.SECONDS);
    }


    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
